package com.qgy.springsecurity.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qgy.springsecurity.dao.UserDao;
import com.qgy.springsecurity.models.MyResult;
import com.qgy.springsecurity.models.bases.SysUser;
import com.qgy.springsecurity.models.views.LoginUser;
import com.qgy.springsecurity.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Objects;

@Service
public class UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDao userDao;

    public MyResult login(SysUser user) {
        try {
            // 1. 构建认证请求
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword(),new ArrayList<>());

            // 2. 触发认证（会走 UserDetailsService 加载用户）
            Authentication authentication = authenticationManager.authenticate(authenticationToken);

            // 3. 设置到安全上下文中（用于后续鉴权）
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 4. 返回统一格式的成功响应（可以扩展为返回 token）
            return MyResult.success().message("登录成功").data(JwtUtil.createJWT(((SysUser)authentication.getPrincipal()).getId().toString(), 1000L * 60));

        } catch (Exception e) {
            e.printStackTrace();
            // 5. 捕获认证失败异常
            System.err.println("用户名或密码错误");
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    public MyResult getUserInfo(String token) {
        Claims claims = JwtUtil.parseJWT(token);
        Long id = Long.valueOf(claims.getSubject());
        SysUser user = userDao.selectOne(new QueryWrapper<>() {{
            eq("id", id);
        }});
        return Objects.isNull(user) ? MyResult.error().message("用户不存在") : MyResult.success().message("查询成功").data(user);
    }
}
